/**
 * 通用工具函数
 * 提供项目中常用的工具方法
 */

/**
 * 格式化时间
 * @param {Date|string|number} date 日期对象、时间戳或日期字符串
 * @param {string} format 格式化模板，默认 'YYYY-MM-DD HH:mm:ss'
 * @returns {string} 格式化后的时间字符串
 */
export const formatTime = (date: Date | string | number, format: string = 'YYYY-MM-DD HH:mm:ss'): string => {
  const d = new Date(date)
  
  if (isNaN(d.getTime())) {
    return ''
  }
  
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hour = String(d.getHours()).padStart(2, '0')
  const minute = String(d.getMinutes()).padStart(2, '0')
  const second = String(d.getSeconds()).padStart(2, '0')
  
  return format
    .replace('YYYY', String(year))
    .replace('MM', month)
    .replace('DD', day)
    .replace('HH', hour)
    .replace('mm', minute)
    .replace('ss', second)
}

/**
 * 格式化金额
 * @param {number|string} amount 金额
 * @param {number} decimals 小数位数，默认2位
 * @returns {string} 格式化后的金额字符串
 */
export const formatAmount = (amount: number | string, decimals: number = 2): string => {
  const num = parseFloat(String(amount))
  
  if (isNaN(num)) {
    return '0.00'
  }
  
  return num.toFixed(decimals)
}

/**
 * 格式化手机号
 * @param {string} phone 手机号
 * @returns {string} 格式化后的手机号（中间4位用*替代）
 */
export const formatPhone = (phone: string): string => {
  if (!phone || phone.length !== 11) {
    return phone
  }
  
  return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
}

/**
 * 验证手机号格式
 * @param {string} phone 手机号
 * @returns {boolean} 是否有效
 */
export const validatePhone = (phone: string): boolean => {
  const phoneRegex = /^1[3-9]\d{9}$/
  return phoneRegex.test(phone)
}

/**
 * 验证邮箱格式
 * @param {string} email 邮箱地址
 * @returns {boolean} 是否有效
 */
export const validateEmail = (email: string): boolean => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  return emailRegex.test(email)
}

/**
 * 防抖函数
 * @param {Function} func 需要防抖的函数
 * @param {number} wait 等待时间（毫秒）
 * @returns {Function} 防抖后的函数
 */
export const debounce = (func: Function, wait: number): Function => {
  let timeout: NodeJS.Timeout | null = null
  
  return function(this: any, ...args: any[]) {
    const context = this
    
    if (timeout) clearTimeout(timeout)
    
    timeout = setTimeout(() => {
      func.apply(context, args)
    }, wait)
  }
}

/**
 * 节流函数
 * @param {Function} func 需要节流的函数
 * @param {number} wait 等待时间（毫秒）
 * @returns {Function} 节流后的函数
 */
export const throttle = (func: Function, wait: number): Function => {
  let timeout: NodeJS.Timeout | null = null
  let previous = 0
  
  return function(this: any, ...args: any[]) {
    const context = this
    const now = Date.now()
    
    if (!previous) previous = now
    
    const remaining = wait - (now - previous)
    
    if (remaining <= 0 || remaining > wait) {
      if (timeout) {
        clearTimeout(timeout)
        timeout = null
      }
      previous = now
      func.apply(context, args)
    } else if (!timeout) {
      timeout = setTimeout(() => {
        previous = Date.now()
        timeout = null
        func.apply(context, args)
      }, remaining)
    }
  }
}

/**
 * 深拷贝对象
 * @param {any} obj 需要拷贝的对象
 * @returns {any} 拷贝后的对象
 */
export const deepClone = (obj: any): any => {
  if (obj === null || typeof obj !== 'object') {
    return obj
  }
  
  if (obj instanceof Date) {
    return new Date(obj.getTime())
  }
  
  if (obj instanceof Array) {
    return obj.map(item => deepClone(item))
  }
  
  if (typeof obj === 'object') {
    const clonedObj: any = {}
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        clonedObj[key] = deepClone(obj[key])
      }
    }
    return clonedObj
  }
  
  return obj
}

/**
 * 获取订单状态文本和样式类名
 * @param {string} status 订单状态
 * @returns {Object} 包含文本和样式类名的对象
 */
export const getOrderStatusInfo = (status: string) => {
  const statusMap: Record<string, { text: string, className: string }> = {
    pending: { text: '待接单', className: 'status-warning' },
    accepted: { text: '已接单', className: 'status-info' },
    preparing: { text: '制作中', className: 'status-primary' },
    delivering: { text: '配送中', className: 'status-warning' },
    completed: { text: '已完成', className: 'status-success' },
    cancelled: { text: '已取消', className: 'status-danger' },
    rejected: { text: '已拒接', className: 'status-danger' }
  }
  
  return statusMap[status] || { text: '未知状态', className: 'status-info' }
}

/**
 * 计算相对时间
 * @param {Date|string|number} date 日期
 * @returns {string} 相对时间描述
 */
export const getRelativeTime = (date: Date | string | number): string => {
  const now = new Date().getTime()
  const targetTime = new Date(date).getTime()
  
  if (isNaN(targetTime)) {
    return ''
  }
  
  const diff = now - targetTime
  const minute = 1000 * 60
  const hour = minute * 60
  const day = hour * 24
  const week = day * 7
  const month = day * 30
  const year = day * 365
  
  if (diff < minute) {
    return '刚刚'
  } else if (diff < hour) {
    return `${Math.floor(diff / minute)}分钟前`
  } else if (diff < day) {
    return `${Math.floor(diff / hour)}小时前`
  } else if (diff < week) {
    return `${Math.floor(diff / day)}天前`
  } else if (diff < month) {
    return `${Math.floor(diff / week)}周前`
  } else if (diff < year) {
    return `${Math.floor(diff / month)}个月前`
  } else {
    return `${Math.floor(diff / year)}年前`
  }
}

/**
 * 存储数据到本地
 * @param {string} key 键名
 * @param {any} data 数据
 * @param {number} expire 过期时间（秒），0表示永不过期
 */
export const setStorage = (key: string, data: any, expire: number = 0): void => {
  try {
    const storageData = {
      data,
      expire: expire > 0 ? Date.now() + expire * 1000 : 0
    }
    wx.setStorageSync(key, JSON.stringify(storageData))
  } catch (error) {
    console.error('存储数据失败', error)
  }
}

/**
 * 从本地获取数据
 * @param {string} key 键名
 * @returns {any} 数据，如果不存在或已过期则返回null
 */
export const getStorage = (key: string): any => {
  try {
    const storageStr = wx.getStorageSync(key)
    if (!storageStr) return null
    
    const storageData = JSON.parse(storageStr)
    
    // 检查是否过期
    if (storageData.expire > 0 && Date.now() > storageData.expire) {
      wx.removeStorageSync(key)
      return null
    }
    
    return storageData.data
  } catch (error) {
    console.error('获取存储数据失败', error)
    return null
  }
}

/**
 * 显示加载提示
 * @param {string} title 提示文本
 */
export const showLoading = (title: string = '加载中...'): void => {
  wx.showLoading({
    title,
    mask: true
  })
}

/**
 * 隐藏加载提示
 */
export const hideLoading = (): void => {
  wx.hideLoading()
}

/**
 * 显示成功提示
 * @param {string} title 提示文本
 * @param {number} duration 持续时间（毫秒）
 */
export const showSuccess = (title: string, duration: number = 2000): void => {
  wx.showToast({
    title,
    icon: 'success',
    duration
  })
}

/**
 * 显示错误提示
 * @param {string} title 提示文本
 * @param {number} duration 持续时间（毫秒）
 */
export const showError = (title: string, duration: number = 2000): void => {
  wx.showToast({
    title,
    icon: 'error',
    duration
  })
}

/**
 * 显示普通提示
 * @param {string} title 提示文本
 * @param {number} duration 持续时间（毫秒）
 */
export const showToast = (title: string, duration: number = 2000): void => {
  wx.showToast({
    title,
    icon: 'none',
    duration
  })
}

/**
 * 确认对话框
 * @param {string} content 内容
 * @param {string} title 标题
 * @returns {Promise<boolean>} 用户是否确认
 */
export const showConfirm = (content: string, title: string = '确认'): Promise<boolean> => {
  return new Promise((resolve) => {
    wx.showModal({
      title,
      content,
      success: (res) => {
        resolve(res.confirm)
      },
      fail: () => {
        resolve(false)
      }
    })
  })
}

/**
 * 检查网络状态
 * @returns {Promise<boolean>} 是否有网络连接
 */
export const checkNetworkStatus = (): Promise<boolean> => {
  return new Promise((resolve) => {
    wx.getNetworkType({
      success: (res) => {
        resolve(res.networkType !== 'none')
      },
      fail: () => {
        resolve(false)
      }
    })
  })
}




